<template>
    <div class="topic-container">
        <div class="toolbar mb-[30px]">
            <t-card>
                <t-row>
                    <t-col :span="3">
                        <div class="add-button">
                            <t-button theme="primary" @click="showFormHandle">
                                <template #icon><t-icon name="add" /></template>
                                发布主题
                            </t-button>
                        </div>
                    </t-col>
                    <t-col :span="3"></t-col>
                    <t-col :span="3"></t-col>
                    <t-col :span="3"></t-col>
                </t-row>
            </t-card>
        </div>
        <div class="table-box">
            <t-card>
                <t-table :loading="loadingStore.getTableLoading" row-key="cs_id" :data="tableData"
                    :columns="tableDataColumns" :stripe="true" :bordered="false" :hover="true" table-layout="auto"
                    size="medium" :pagination="tablePagination" :show-header="true" cell-empty-content="-" lazy-load
                    :onPageChange="changeTablePage" />
            </t-card>
        </div>

        <client-only>
            <div class="form-box">
                <t-dialog v-model:visible="showForm" :header="formTitle" width="60%" :confirm-on-enter="false"
                    :closeOnOverlayClick="false" :on-close="close" :on-confirm="onConfirmAnother">
                    <t-space direction="vertical" style="width: 100%">
                        <div>
                            <t-form>
                                <t-row>
                                    <t-col :span="6">
                                        <t-form-item label="主题标题" name="title">
                                            <t-input placeholder="请输入主题标题" v-model="formData.content.title" />
                                        </t-form-item>
                                    </t-col>
                                    <t-col :span="6">
                                        <t-form-item label="主题分类" name="cid">
                                            <t-select v-model="formData.content.cid">
                                                <t-option v-for="(item, index) in categoryList" :key="item.cid"
                                                    :label="item.title" :value="item.cid" />
                                            </t-select>
                                        </t-form-item>
                                    </t-col>
                                    <span class="mt-[30px]"></span>
                                    <t-col :span="6">
                                        <t-form-item label="主题描述" name="description">
                                            <t-textarea v-model="formData.content.description" placeholder="主题描述"
                                                name="description" :autosize="{ minRows: 6, maxRows: 6 }" />
                                        </t-form-item>
                                    </t-col>
                                    <t-col :span="6">
                                        <t-form-item label="缩略图" name="thumbnail">
                                            <t-upload ref="thumbnailRef" v-model="thumbnailFile"
                                                :image-viewer-props="imageViewerProps" :size-limit="sizeLimit"
                                                :action="upload2CloudFlare" theme="image" tips="请选择主题缩略图"
                                                accept="image/*" :disabled="false" name="file" :auto-upload="true"
                                                :show-image-file-name="true" :upload-all-files-in-one-request="false"
                                                :headers="uploadToken" @select-change="getLocalToken"
                                                :data="{ dir: 'thumbnail' }" @success="uploadThumbnailSuccess"
                                                @remove="removeThumbnail" :locale="{
                        triggerUploadText: {
                            image: '请选择图片',
                        },
                    }" @fail="handleFail">

                                            </t-upload>
                                        </t-form-item>
                                    </t-col>
                                    <t-col :span="6">
                                        <t-form-item label="主题分类" name="type">
                                            <t-select v-model="formData.content.type">
                                                <t-option v-for="(item, index) in topicTypeList" :key="item.type"
                                                    :label="item.title" :value="item.type" />
                                            </t-select>
                                        </t-form-item>
                                    </t-col>
                                    <t-col :span="6">
                                        <t-form-item label="Banner" name="is_banner">
                                            <t-radio-group v-model="formData.content.is_banner">
                                                <t-radio-button :value="0">否</t-radio-button>
                                                <t-radio-button :value="1">是</t-radio-button>
                                            </t-radio-group>
                                        </t-form-item>
                                    </t-col>
                                    <t-col :span="6">
                                        <t-form-item label="是否推荐" name="is_recommend">
                                            <t-radio-group v-model="formData.content.is_recommend">
                                                <t-radio-button :value="0">不推荐</t-radio-button>
                                                <t-radio-button :value="1">推荐</t-radio-button>
                                            </t-radio-group>
                                        </t-form-item>
                                    </t-col>
                                    <t-col :span="12">
                                        <t-form-item label="主题正文" name="content">
                                            <wang-editor ref="topicEditorRef"
                                                :initial-content="formData.content.content"></wang-editor>
                                        </t-form-item>
                                    </t-col>
                                </t-row>
                            </t-form>
                        </div>
                    </t-space>
                </t-dialog>
            </div>
        </client-only>
    </div>
</template>

<script setup lang="tsx">
import { upload2CloudFlare } from '~/utils/request';
import { useLoading } from '~/store/manager/loading';


definePageMeta({
    layout: 'manager'
})

// store
const loadingStore = useLoading();

// 表格数据
const tableData = ref([]);
// 表格显示列
const tableDataColumns = [
    {
        colKey: 'cs_id',
        title: '主题ID',
        width: 100
    },
    {
        colKey: 'thumbnail',
        title: '缩略图',
        width: 150,
        cell: (h, { row }) => {
            if (row.thumbnail == null) {
                return (
                    <div class="topic-thumbnail">
                        无缩略图
                    </div>
                )
            } else {
                return (
                    <div class="topic-thumbnail">
                        <t-image src={row.thumbnail} fit="cover" class="w-[100px] h-[50px]" />
                    </div>
                )
            }
        }
    },
    {
        colKey: 'category[0].title',
        title: '主题分类',
        width: 150
    },
    {
        colKey: 'title',
        title: '主题标题',
        width: 350,
        ellipsis: true
    },
    {
        colKey: 'like',
        title: '主题点赞',
        width: 130
    },
    {
        colKey: 'click',
        title: '主题点击',
        width: 130
    },
    {
        colKey: 'opearate',
        title: '操作',
        cell: (h, { row }) => (
            <div class="opearate">
                <t-button theme="success" shape="square" size="small" variant="base" onClick={() => {
                    // 设置表单类型为编辑
                    createForm.value = false;
                    formData.content = { ...row };
                    formData.content.content = row.content_detail[0].content;
                    thumbnailFile.value = row.thumbnail === null ? [] : [{ url: row.thumbnail }]
                    // 显示表单对话框
                    showForm.value = true;
                }}><t-icon name="edit" /></t-button>
            </div>
        )
    }
]
// 表格分页信息
const tablePagination = reactive({
    defaultCurrent: 1,
    defaultPageSize: 10,
    total: 0
})

// 是否是新建表单
const createForm = ref(true);
// 显示表单flag
const showForm = ref(false);
// 表单标题
const formTitle = ref('新增');
// 表单主题分类
const categoryList = ref([])
// 表单主题类型
const topicTypeList = [
    {
        type: 'topic',
        title: '文字主题'
    },
    {
        type: 'timeline',
        title: '时间轴'
    }
];
// 缩略图上传ref
const thumbnailRef = ref();
// 缩略图文件信息
const thumbnailFile = ref([]);
// 缩略图文件大小
const sizeLimit = ref({ size: 500, unit: 'MB' });
// 缩略图预览
const imageViewerProps = ref({ closeOnEscKeydown: false });
// 表单正文编辑器ref
const topicEditorRef = ref(null);
// token
const uploadToken = ref({});
// 获取本地token
const getLocalToken = () => {
    const tokenInfo: any = localStorage.getItem('token');

    let token: any = ''
    if (tokenInfo !== null || tokenInfo !== undefined) {
        // 本地存在token信息，格式化token
        token = JSON.parse(tokenInfo);
        token = token.token_type + ' ' + token.access_token
        uploadToken.value = { Authorization: token };
        return;
    }

    MessagePlugin.error({
        content: '本地Token无效或者不存在'
    })
}
// 缩略图上传成功
const uploadThumbnailSuccess = (context) => {
    const res = context.response;
    if (res.errno === 0) {
        MessagePlugin.success({
            content: res.message
        });
        formData.content.thumbnail = res.data.url;
    } else {
        MessagePlugin.error({
            content: res.message
        });
    }

}
// 缩略图删除
const removeThumbnail = () => {
    formData.content.thumbnail = '';
}


// 表单数据
const formData = reactive({
    content: {
        flag: 'create',
        cs_id: 0,
        status: 0,
        title: '',
        cid: '',
        type: 'topic',
        description: '',
        thumbnail: '',
        like: 0,
        click: 0,
        author: 0,
        content: '',
        is_banner: 0,
        is_recommend: 0
    }
})
// 表单显示/隐藏事件catch
const showFormHandle = () => {
    showForm.value ? showForm.value = false : showForm.value = true;
}
// 重置表单
const resetFormData = () => {
    let tmpData = {
        flag: 'create',
        cs_id: 0,
        status: 0,
        title: '',
        cid: '',
        type: 'topic',
        description: '',
        thumbnail: '',
        like: 0,
        click: 0,
        author: 0,
        content: '',
        is_banner: 0,
        is_recommend: 0
    };
    formData.content = tmpData;
    thumbnailFile.value = [];
    // topicEditorRef.value.valueHtml = "";

    createForm.value = true;
}
// 表单关闭事件
const close = () => {
    resetFormData();
}
// 表单提交事件
const onConfirmAnother = () => {
    // 改变操作flasg
    if (createForm.value) {
        formData.content.flag = 'create';
    } else {
        formData.content.flag = 'update';
    }
    formData.content.content = topicEditorRef.value.valueHtml;
    // 访问数据库
    create_content(formData.content).then((res) => {
        MessagePlugin.success({
            content: res.message
        });
        // 刷新页面
        showForm.value = false;
        // 重置表单
        resetFormData();
        // 重新载入页面
        __initialize();

    }).catch((err) => {
        console.log(err);
    })

}
// 缩略图上传失败
const handleFail = ({ file }) => {
    MessagePlugin.error(`文件 ${file.name} 上传失败`);
};

// 表格分页切换
const changeTablePage = (pageInfo: any, newData: any) => {
    // 请求数据
    get_content_list({ flag: 'table', page: pageInfo.current, size: pageInfo.pageSize }).then((res: any) => {
        tableData.value = res.data.list;
        tablePagination.defaultCurrent = res.data.page;
        tablePagination.defaultPageSize = res.data.size;
        tablePagination.total = res.data.total;
    }).catch((err) => {
        console.log(err);
    })
}


// 页面初始化
const __initialize = () => {
    // 获取表格数据
    get_content_list({ flag: 'table', page: tablePagination.defaultCurrent, size: tablePagination.defaultPageSize }).then((res: any) => {
        tableData.value = res.data.list;
        tablePagination.defaultCurrent = res.data.page;
        tablePagination.defaultPageSize = res.data.size;
        tablePagination.total = res.data.total;
    }).catch((err) => {
        console.log(err);
    });

    // 初始化表单主题发布分类列表
    get_category_list({ flag: 'usable' }).then((res) => {
        categoryList.value = res.data;
    }).catch((err) => {
        console.log(err);
    })
}

// 页面载入
onMounted(() => {
    __initialize();
})

// 计算属性及监视器
watch(createForm, (value, oldValue) => {
    if (value) {
        formTitle.value = '新增';
    } else {
        formTitle.value = '编辑';
    }
})
</script>

<style scoped>
:deep() {

    .t-col-6,
    .t-col-12 {
        margin-top: 15px !important;
    }
}
</style>